<?php

namespace app\uniapp\controller;

use app\common\exception\MiException;
use app\common\service\CommonDistService;
use app\common\service\CommonSiteConfigService;
use app\common\service\CommonStoreManagerService;
use app\common\service\pay\WxpayService;
use app\model\site\User;
use app\model\store\DistCashApply;
use app\model\store\DistRewardLog;
use app\model\store\Order;
use app\model\store\StoreManager;
use app\model\store\StoreManagerBalanceLog;
use app\uniapp\middleware\CheckLogin;
use app\uniapp\service\UniAuthService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\response\Json;

class UserDistController extends UniController
{
    protected array $middleware = [
        CheckLogin::class,
    ];
    /**
     * @throws DbException
     */
    public function team(): Json
    {


        $levelType = $this->param('level_type');
        $userId = UniAuthService::instance()->getLoginId();

        $list = CommonDistService::instance()->teamQuery($userId, $levelType)
            ->filter(function ($v) use($userId) {
                $v['provideReward'] = DistRewardLog::where('from_user_id', $v['id'])->where('user_id', $userId)->sum('amount');
                $v['createTime'] = miDate('Y-m-d', $v['create_time']);
                return $v;
            })
            ->paginate(20);

        return jsonSuccess([
            'items' => $list->items(),
            'total' => $list->total(),
        ]);
    }

    /**
     * 分销数据概览
     * @return Json
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function console(): Json
    {
        $user = UniAuthService::instance()->getLoginInfo();
        $userId = $user->id;
        $storeManager = StoreManager::where('user_id', $userId)->find();
        // 团队人数
        $userNum = CommonDistService::instance()->teamQuery($userId)->count();
        // 团队订单数量
        $userIds = CommonDistService::instance()->teamQuery($userId)->column("id");
        $orderNum = Order::where('user_id', 'in', $userIds)->count();
        // 团队总业绩
        $totalOrderPrice = CommonStoreManagerService::instance()->getTotalPriceByManagerId($storeManager->id);
        // 业绩比例
        $month = date('Y-m');
        $monthRewardRate = CommonStoreManagerService::instance()->getManagerRate($storeManager->id, $month);
        // 本月邀请店长的数量
        $storeManagerNum = CommonStoreManagerService::instance()->getManagerNumMonth($storeManager->id, $month);

        return jsonSuccess([
            'console' => [
                'totalReward' => $user->total_reward,
                'reward' => $user->reward,
                'userNum' => $userNum,
                'orderNum' => $orderNum,
                'totalOrderPrice' => $totalOrderPrice,
                'monthRewardRate' => $monthRewardRate*100 . '%',
                'storeManagerNum' => $storeManagerNum,
                'month' => $month,
            ]
        ]);
    }

    /**
     * 佣金明细分页列表
     * @throws DbException
     */
    public function rewardLogPaginate(): \think\response\Json
    {
        $userId = UniAuthService::instance()->getLoginId();
        $list = DistRewardLog::where('user_id', $userId)->paginate(20);
        return jsonSuccess([
            'items' => $list->items(),
            'total' => $list->total(),
        ]);
    }


    // 提现
    public function cash(): Json
    {

        $amount = $this->post('amount');
        $userId = UniAuthService::instance()->getLoginId();

        Db::startTrans();

        try {
            $user = User::lock(true)->find($userId);
            if ($user->reward < $amount){
                throw new MiException("余额不足");
            }

            // 扣除佣金
            $user->reward -= $amount;
            $user->save();

            // 创建提现申请
            DistCashApply::create([
                'site_id' => $user->site_id,
                'user_id' => $userId,
                'amount' => $amount,
            ]);

            Db::commit();
        }catch (\Exception $e) {
            Db::rollback();
            return jsonError($e->getMessage());
        }

        return jsonSuccess();
    }

    /**
     * 提现申请记录分页列表
     * @throws DbException
     */
    public function cashApplyPaginate(): \think\response\Json
    {
        $userId = UniAuthService::instance()->getLoginId();
        $where = [
            ['user_id', '=', $userId],
        ];
        $audit = $this->param('audit', '');
        if ($audit !== ''){
            $where[] = ['audit', '=', $audit];
        }
        $list = DistCashApply::where($where)->order('create_time desc')->paginate(20);
        return jsonSuccess([
            'items' => $list->items(),
            'total' => $list->total(),
        ]);
    }


    /**
     * 店长申请
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws MiException
     * @throws ModelNotFoundException
     */
    public function storeManagerApply(): Json
    {
        $post = $this->post('');
        validate([
            'title'  => 'require',
            'image'   => 'require',
            'realname' => 'require',
            'mobile' => 'require',
        ],[
            'title' => '店铺名称必须',
            'image'     => '店铺图片必填',
            'realname'   => '姓名必填',
            'mobile'  => '手机号必填',
        ])->check($post);
        $siteId = UniAuthService::instance()->getSiteId();
        $uid = UniAuthService::instance()->getLoginId();
        $distConfig = CommonSiteConfigService::instance()->getConfigValue($siteId, CommonSiteConfigService::DIST);
        $post['site_id'] = $siteId;
        $post['user_id'] = $uid;
        $post['audit_status'] = 0;
        // 查询是否申请过
        $storeManager = StoreManager::where('user_id', $uid)->find();
        if ($storeManager){
            $storeManager = StoreManager::update($post, ['id'=>$storeManager->id]);
        }else{
            // 未付款
            $post['pay_time'] = 0;
            // 样品基金余额
            $post['balance'] = $distConfig['store_manager_price'];
            $storeManager = StoreManager::create($post);
        }
        return jsonSuccess([
            'info' => $storeManager
        ]);
    }

    /**
     * 申请店长付款
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws MiException
     */
    public function storeManagerPay(): Json
    {

        Db::startTrans();
        try {
            $id = $this->post('id');
            $openid = $this->post('openid');
            $manager = StoreManager::lock(true)->find($id);
            // 每次付款重新生成一个新的订单号
            $manager->order_no = makeOrderNo('SMA');
            $manager->save();

            $config = CommonSiteConfigService::instance()->getWxPayConfig($manager->site_id);
            $distConfig = CommonSiteConfigService::instance()->getConfigValue($manager->site_id, CommonSiteConfigService::DIST);
            $wxPayService = WxpayService::getInstance($config);
            $notify = request()->domain() . '/common/public/wxPayNotifyStoreManager/id/'.$manager->site_id;
            $res = $wxPayService->jsapi($manager->order_no, $distConfig['store_manager_price'], $openid, '申请店长', $notify);
            Db::commit();

            return jsonSuccess([
                'pay' => $res,
            ]);

        }catch (\Exception $e){
            Db::rollback();
            throw $e;
        }
    }

    /** 获取店长信息
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function storeManager(): Json
    {
        $uid = $this->param('user_id');
        $info = StoreManager::where('user_id', $uid)->find();
        return jsonSuccess([
            'info' => $info,
        ]);

    }

    /**
     * 样品基金明细分页列表
     * @throws DbException
     */
    public function balanceLogPaginate(): \think\response\Json
    {
        $userId = UniAuthService::instance()->getLoginId();
        $list = StoreManagerBalanceLog::where('user_id', $userId)->paginate(20);
        return jsonSuccess([
            'items' => $list->items(),
            'total' => $list->total(),
        ]);
    }



}
